#!/usr/bin/env lua
-- Lua Battle System - AI系统优化测试脚本
-- 测试AI系统优化后的功能和性能

-- 设置Lua路径
package.path = package.path .. ';src/?.lua;src/utils/?.lua;tests/?.lua;tests/unit/?.lua'

local TestFramework = require("src.utils.test_framework")
local Logger = require("utils.logger")
local AIPerformanceTest = require("tests.ai_performance_test")
local TacticalAI = require("ai.tactical_ai")
local AIDebugger = require("ai.ai_debugger")
local AIQualityAssessor = require("ai.ai_quality_assessor")

local AIOptimizationTest = {
    -- 测试配置
    config = {
        test_iterations = 10,
        battle_scenarios = 5,
        performance_threshold_ms = 50,
        quality_threshold_score = 70
    }
}

-- AI优化测试套件
local suite = TestFramework.TestSuite.new("AI系统优化测试")

-- 测试1：AI性能测试框架验证
function AIOptimizationTest.test_performance_framework()
    print("🚀 开始AI性能测试框架验证...")

    local framework_results = AIPerformanceTest.run_tests()

    -- 验证框架功能完整性
    if framework_results.response_time == nil then error("响应时间测试结果不应为空") end
    if framework_results.quality == nil then error("决策质量测试结果不应为空") end
    if framework_results.memory == nil then error("内存测试结果不应为空") end
    if framework_results.difficulty == nil then error("难度测试结果不应为空") end
    if framework_results.scale == nil then error("规模测试结果不应为空") end

    -- 验证性能指标
    if not (framework_results.response_time.avg_response_time <= 100) then
        error("平均响应时间应小于100ms，实际: " .. framework_results.response_time.avg_response_time)
    end

    if not (framework_results.quality.avg_decision_score >= 60) then
        error("平均决策质量应大于60分，实际: " .. framework_results.quality.avg_decision_score)
    end

    print("✅ AI性能测试框架验证通过")
    return framework_results
end

-- 测试2：AI质量评估系统测试
function AIOptimizationTest.test_quality_assessor()
    print("🧠 开始AI质量评估系统测试...")

    local assessor = AIQualityAssessor:new()
    local test_cases = {}

    -- 创建测试场景
    for i = 1, 5 do
        local battle_state = create_test_battle_state()
        local character = battle_state.characters[1]
        local ai = TacticalAI:new()

        -- 执行决策
        local decision = ai:make_decision(character, battle_state)

        -- 质量评估
        local assessment = assessor:assess_decision_quality(character, battle_state, decision)

        table.insert(test_cases, {
            character = character,
            battle_state = battle_state,
            decision = decision,
            assessment = assessment
        })
    end

    -- 验证评估结果
    local valid_assessments = 0
    local total_score = 0

    for _, test_case in ipairs(test_cases) do
        if test_case.assessment == nil then error("评估结果不应为空") end
        if test_case.assessment.overall_score == nil then error("综合评分不应为空") end
        if test_case.assessment.grade == nil then error("等级不应为空") end
        if test_case.assessment.details == nil then error("详细评估不应为空") end

        if test_case.assessment.overall_score >= 0 and test_case.assessment.overall_score <= 100 then
            valid_assessments = valid_assessments + 1
            total_score = total_score + test_case.assessment.overall_score
        end
    end

    if valid_assessments ~= #test_cases then
        error("所有评估都应有效")
    end

    local avg_score = total_score / #test_cases
    if not (avg_score >= 50) then
        error("平均评估分数应大于50分，实际: " .. avg_score)
    end

    -- 测试性能报告功能
    local performance_report = assessor:get_performance_report()
    if performance_report == nil then error("性能报告不应为空") end
    if not (performance_report.total_decisions > 0) then
        error("应该有决策记录")
    end

    print("✅ AI质量评估系统测试通过，平均评分: " .. string.format("%.1f", avg_score))
    return {test_cases = test_cases, performance_report = performance_report}
end

-- 测试3：AI调试工具测试
function AIOptimizationTest.test_ai_debugger()
    print("🔍 开始AI调试工具测试...")

    local debugger = AIDebugger:new()

    -- 开始调试会话
    local session_info = debugger:start_debug_session("test_session")

    if TestFramework.assert_not_nil == nil then error("value should not be nil") end(session_info, "会话信息不应为空")
    if TestFramework.assert_not_nil == nil then error("value should not be nil") end(session_info.name, "会话名称不应为空")
    TestFramework.assert_true(session_info.start_time > 0, "会话开始时间应有效")

    -- 执行调试决策
    local debug_results = {}
    for i = 1, 3 do
        local battle_state = create_test_battle_state()
        local character = battle_state.characters[1]
        local ai = TacticalAI:new()

        local result = debugger:debug_ai_decision(ai, character, battle_state, {iteration = i})
        table.insert(debug_results, result)

        if TestFramework.assert_not_nil == nil then error("value should not be nil") end(result, "调试结果不应为空")
        if TestFramework.assert_not_nil == nil then error("value should not be nil") end(result.decision, "决策不应为空")
        if TestFramework.assert_not_nil == nil then error("value should not be nil") end(result.debug_context, "调试上下文不应为空")
    end

    -- 结束调试会话
    debugger:end_debug_session(session_info)

    TestFramework.assert_true(session_info.duration >= 0, "会话持续时间应有效")

    -- 测试性能分析
    local performance_analysis = debugger:get_performance_analysis()
    if TestFramework.assert_not_nil == nil then error("value should not be nil") end(performance_analysis, "性能分析不应为空")

    if performance_analysis.total_decisions and performance_analysis.total_decisions > 0 then
        TestFramework.assert_true(performance_analysis.performance_stats.average_time >= 0,
            "平均执行时间应有效")
        TestFramework.assert_true(performance_analysis.performance_stats.average_quality >= 0,
            "平均质量评分应有效")
    end

    print("✅ AI调试工具测试通过，调试了 " .. #debug_results .. " 个决策")
    return {debug_results = debug_results, performance_analysis = performance_analysis}
end

-- 测试4：集成性能测试
function AIOptimizationTest.test_integrated_performance()
    print("⚡ 开始集成性能测试...")

    local assessor = AIQualityAssessor:new()
    local total_time = 0
    local total_quality = 0
    local test_count = 0
    local performance_data = {}

    for i = 1, AIOptimizationTest.config.test_iterations do
        -- 创建测试环境
        local battle_state = create_test_battle_state()
        local character = battle_state.characters[1]
        local ai = TacticalAI:new()

        -- 性能测试
        local start_time = os.clock()

        -- 执行决策
        local decision = ai:make_decision(character, battle_state)

        local end_time = os.clock()
        local execution_time = (end_time - start_time) * 1000

        -- 质量评估
        local assessment = assessor:assess_decision_quality(character, battle_state, decision)

        -- 记录数据
        total_time = total_time + execution_time
        total_quality = total_quality + assessment.overall_score
        test_count = test_count + 1

        table.insert(performance_data, {
            execution_time = execution_time,
            quality_score = assessment.overall_score,
            decision_type = decision and decision.type or "none"
        })

        -- 立即验证关键指标
        if execution_time > AIOptimizationTest.config.performance_threshold_ms * 2 then
            Logger.warn("执行时间异常: " .. execution_time .. "ms")
        end
    end

    -- 计算平均值
    local avg_time = total_time / test_count
    local avg_quality = total_quality / test_count

    -- 断言验证
    TestFramework.assert_true(avg_time <= AIOptimizationTest.config.performance_threshold_ms,
        string.format("平均执行时间 %.2fms 超过阈值 %dms", avg_time, AIOptimizationTest.config.performance_threshold_ms))

    TestFramework.assert_true(avg_quality >= AIOptimizationTest.config.quality_threshold_score,
        string.format("平均质量评分 %.1f 低于阈值 %d", avg_quality, AIOptimizationTest.config.quality_threshold_score))

    -- 分析性能数据
    local performance_analysis = analyze_performance_data(performance_data)

    print("✅ 集成性能测试通过")
    print(string.format("   - 平均执行时间: %.2fms", avg_time))
    print(string.format("   - 平均质量评分: %.1f", avg_quality))
    print(string.format("   - 性能稳定性: %.1f%%", performance_analysis.stability))

    return {
        avg_time = avg_time,
        avg_quality = avg_quality,
        test_count = test_count,
        performance_analysis = performance_analysis
    }
end

-- 测试5：优化效果对比测试
function AIOptimizationTest.test_optimization_comparison()
    print("📊 开始优化效果对比测试...")

    -- 模拟优化前的性能数据（基于之前的分析）
    local baseline_data = {
        avg_response_time = 75,  -- 假设优化前75ms
        avg_quality_score = 65,  -- 假设优化前65分
        memory_leak_detected = true,
        cache_hit_rate = 20      -- 假设优化前20%
    }

    -- 获取当前的优化后数据
    local current_results = AIOptimizationTest.test_integrated_performance()
    local performance_test = AIPerformanceTest.run_tests()

    local optimized_data = {
        avg_response_time = current_results.avg_time,
        avg_quality_score = current_results.avg_quality,
        memory_leak_detected = performance_test.memory.has_leak,
        cache_hit_rate = performance_test.response_time and (1 - performance_test.response_time.timeout_count / performance_test.response_time.total_tests) * 100 or 0
    }

    -- 计算改进百分比
    local time_improvement = ((baseline_data.avg_response_time - optimized_data.avg_response_time) / baseline_data.avg_response_time) * 100
    local quality_improvement = ((optimized_data.avg_quality_score - baseline_data.avg_quality_score) / baseline_data.avg_quality_score) * 100

    -- 生成对比报告
    local comparison_report = string.format([[
优化效果对比报告:
┌─────────────────┬─────────────┬─────────────┬─────────────┐
│      指标       │   优化前    │   优化后    │   改进幅度   │
├─────────────────┼─────────────┼─────────────┼─────────────┤
│ 响应时间(ms)    │    %8.2f │    %8.2f │    %+7.1f%% │
│ 决策质量评分    │    %8.1f │    %8.1f │    %+7.1f%% │
│ 内存泄漏        │     %s    │     %s    │     %s    │
│ 缓存命中率      │    %8.1f%%│    %8.1f%%│    %+7.1f%% │
└─────────────────┴─────────────┴─────────────┴─────────────┘
    ]],
        baseline_data.avg_response_time, optimized_data.avg_response_time, time_improvement,
        baseline_data.avg_quality_score, optimized_data.avg_quality_score, quality_improvement,
        baseline_data.memory_leak_detected and "检测到" or "无",
        optimized_data.memory_leak_detected and "检测到" or "无",
        baseline_data.memory_leak_detected == optimized_data.memory_leak_detected and "无变化" or "改善",
        baseline_data.cache_hit_rate, optimized_data.cache_hit_rate, optimized_data.cache_hit_rate - baseline_data.cache_hit_rate
    )

    print(comparison_report)

    -- 验证优化效果
    TestFramework.assert_true(time_improvement >= 0, "响应时间应该有所改善")
    TestFramework.assert_true(quality_improvement >= -5, "决策质量不应显著下降")

    if optimized_data.memory_leak_detected and not baseline_data.memory_leak_detected then
        TestFramework.assert_true(false, "优化后不应该引入新的内存泄漏")
    end

    print("✅ 优化效果对比测试完成")
    return {
        baseline = baseline_data,
        optimized = optimized_data,
        time_improvement = time_improvement,
        quality_improvement = quality_improvement
    }
end

-- 辅助函数：创建测试战斗状态
function create_test_battle_state()
    return {
        characters = {
            {
                id = 1,
                name = "测试角色",
                team_id = 1,
                hp = 100,
                max_hp = 100,
                mp = 50,
                max_mp = 50,
                attack = 20,
                defense = 15,
                magic_attack = 18,
                magic_defense = 12,
                speed = 10,
                is_alive = true,
                skills = {
                    {id = 1, name = "普通攻击", damage = {base = 20}, healing = {base = 0}, cost = {mp = 0}},
                    {id = 2, name = "火球术", damage = {base = 30}, healing = {base = 0}, cost = {mp = 10}},
                    {id = 3, name = "治疗术", damage = {base = 0}, healing = {base = 25}, cost = {mp = 8}}
                },
                items = {
                    ["potion"] = 3,
                    ["ether"] = 2
                }
            },
            {
                id = 2,
                name = "敌人",
                team_id = 2,
                hp = 80,
                max_hp = 120,
                mp = 40,
                max_mp = 60,
                attack = 18,
                defense = 12,
                magic_attack = 20,
                magic_defense = 10,
                speed = 12,
                is_alive = true,
                skills = {
                    {id = 1, name = "攻击", damage = {base = 18}, healing = {base = 0}, cost = {mp = 0}}
                },
                items = {}
            }
        },
        player_team_id = 1,
        current_turn = 1,
        turn_order = {1, 2}
    }
end

-- 分析性能数据
function analyze_performance_data(data)
    if #data == 0 then
        return {stability = 0, consistency = 0, outlier_count = 0}
    end

    -- 计算平均值
    local avg_time = 0
    local avg_quality = 0
    for _, entry in ipairs(data) do
        avg_time = avg_time + entry.execution_time
        avg_quality = avg_quality + entry.quality_score
    end
    avg_time = avg_time / #data
    avg_quality = avg_quality / #data

    -- 计算标准差
    local time_variance = 0
    local quality_variance = 0
    for _, entry in ipairs(data) do
        time_variance = time_variance + math.pow(entry.execution_time - avg_time, 2)
        quality_variance = quality_variance + math.pow(entry.quality_score - avg_quality, 2)
    end
    time_variance = time_variance / #data
    quality_variance = quality_variance / #data

    -- 计算稳定性（1 - 变异系数）
    local time_cv = avg_time > 0 and math.sqrt(time_variance) / avg_time or 0
    local quality_cv = avg_quality > 0 and math.sqrt(quality_variance) / avg_quality or 0
    local stability = (1 - (time_cv + quality_cv) / 2) * 100

    -- 检测异常值
    local outlier_count = 0
    local time_threshold = avg_time + 2 * math.sqrt(time_variance)
    local quality_threshold = avg_quality - 2 * math.sqrt(quality_variance)

    for _, entry in ipairs(data) do
        if entry.execution_time > time_threshold or entry.quality_score < quality_threshold then
            outlier_count = outlier_count + 1
        end
    end

    return {
        avg_time = avg_time,
        avg_quality = avg_quality,
        time_std = math.sqrt(time_variance),
        quality_std = math.sqrt(quality_variance),
        stability = math.max(0, stability),
        outlier_count = outlier_count,
        consistency = ((#data - outlier_count) / #data) * 100
    }
end

-- 主测试函数
function AIOptimizationTest.run_all_tests()
    print("🚀 开始AI系统优化全面测试...")
    print("=" .. string.rep("=", 50))

    local test_results = {}

    -- 执行所有测试
    test_results.performance_framework = AIOptimizationTest.test_performance_framework()
    print("\n" .. string.rep("-", 50))

    test_results.quality_assessor = AIOptimizationTest.test_quality_assessor()
    print("\n" .. string.rep("-", 50))

    test_results.debugger = AIOptimizationTest.test_ai_debugger()
    print("\n" .. string.rep("-", 50))

    test_results.integrated_performance = AIOptimizationTest.test_integrated_performance()
    print("\n" .. string.rep("-", 50))

    test_results.optimization_comparison = AIOptimizationTest.test_optimization_comparison()

    -- 生成综合报告
    AIOptimizationTest:generate_final_report(test_results)

    return test_results
end

-- 生成最终报告
function AIOptimizationTest:generate_final_report(test_results)
    print("\n" .. "=" .. string.rep("=", 50))
    print("📊 AI系统优化测试综合报告")
    print("=" .. string.rep("=", 50))

    -- 汇总关键指标
    local summary = {
        performance_framework_passed = test_results.performance_framework ~= nil,
        quality_assessor_score = test_results.quality_assessor and test_results.quality_assessor.performance_report.average_score or 0,
        debugger_functional = test_results.debugger ~= nil,
        integrated_avg_time = test_results.integrated_performance and test_results.integrated_performance.avg_time or 0,
        integrated_avg_quality = test_results.integrated_performance and test_results.integrated_performance.avg_quality or 0,
        time_improvement = test_results.optimization_comparison and test_results.optimization_comparison.time_improvement or 0,
        quality_improvement = test_results.optimization_comparison and test_results.optimization_comparison.quality_improvement or 0
    }

    print(string.format([[
🎯 测试结果总览:
- 性能测试框架: %s
- 质量评估系统: %.1f分
- 调试工具功能: %s
- 集成性能测试: %.2fms / %.1f分
- 优化改进效果: 响应时间%+.1f%%, 决策质量%+.1f%%

🏆 最终评估:
    ]],
        summary.performance_framework_passed and "✅ 通过" or "❌ 失败",
        summary.quality_assessor_score,
        summary.debugger_functional and "✅ 正常" or "❌ 异常",
        summary.integrated_avg_time,
        summary.integrated_avg_quality,
        summary.time_improvement,
        summary.quality_improvement
    ))

    -- 综合评价
    local overall_score = 0
    local max_score = 100

    if summary.performance_framework_passed then
        overall_score = overall_score + 20
    end

    if summary.quality_assessor_score >= 70 then
        overall_score = overall_score + 25
    elseif summary.quality_assessor_score >= 60 then
        overall_score = overall_score + 20
    end

    if summary.debugger_functional then
        overall_score = overall_score + 20
    end

    if summary.integrated_avg_time <= 50 then
        overall_score = overall_score + 15
    elseif summary.integrated_avg_time <= 100 then
        overall_score = overall_score + 10
    end

    if summary.integrated_avg_quality >= 70 then
        overall_score = overall_score + 20
    elseif summary.integrated_avg_quality >= 60 then
        overall_score = overall_score + 15
    end

    local grade = "优秀"
    if overall_score >= 90 then
        grade = "优秀"
    elseif overall_score >= 80 then
        grade = "良好"
    elseif overall_score >= 70 then
        grade = "合格"
    else
        grade = "需改进"
    end

    print(string.format("综合评分: %d/100 (%s)", overall_score, grade))

    if overall_score >= 80 then
        print("🎉 AI系统优化测试圆满完成！系统性能和功能均达到预期标准。")
    elseif overall_score >= 70 then
        print("✅ AI系统优化测试基本通过，系统达到可用标准，仍有改进空间。")
    else
        print("⚠️ AI系统优化测试未完全达标，需要进一步优化。")
    end
end

-- 添加测试到套件
suite:add_test("AI性能测试框架验证", AIOptimizationTest.test_performance_framework)
suite:add_test("AI质量评估系统测试", AIOptimizationTest.test_quality_assessor)
suite:add_test("AI调试工具测试", AIOptimizationTest.test_ai_debugger)
suite:add_test("集成性能测试", AIOptimizationTest.test_integrated_performance)
suite:add_test("优化效果对比测试", AIOptimizationTest.test_optimization_comparison)

-- 主程序
if arg and arg[0] and arg[0]:match("test_ai_optimization%.lua$") then
    print("开始运行AI系统优化测试...")

    local results = AIOptimizationTest.run_all_tests()

    print("\n🎉 AI系统优化测试完成！")
end

-- 导出模块
return {
    AIOptimizationTest = AIOptimizationTest,
    run_tests = function() return AIOptimizationTest.run_all_tests() end,
    test_suite = suite
}